<template>
  <view class="page-container">
    <!-- 顶部标题 -->
    <view class="header">
      <view class="title">选择展览</view>
      <view class="subtitle">从您的展览中选择图片进行创作</view>
    </view>

    <!-- 加载状态 -->
    <view v-if="isLoading" class="loading-container">
      <text class="loading-text">加载展览列表中...</text>
    </view>

    <!-- 空状态 -->
    <view v-else-if="exhibitions.length === 0" class="empty-container">
      <view class="empty-icon">🖼️</view>
      <text class="empty-text">暂无展览</text>
      <text class="empty-hint">您还没有创建任何展览</text>
      <button class="create-btn" @click="createNewExhibition">创建新展览</button>
    </view>

    <!-- 展览列表 -->
    <view v-else class="exhibition-list">
      <view 
        v-for="exhibition in exhibitions" 
        :key="exhibition.recordId"
        class="exhibition-card"
        @click="selectExhibition(exhibition)"
      >
        <view class="exhibition-image">
          <image 
            :src="exhibition.coverImage || '/static/default-exhibition.png'" 
            mode="aspectFill"
            class="cover-img"
          />
        </view>
        <view class="exhibition-info">
          <view class="exhibition-title">{{ exhibition.title }}</view>
          <view class="exhibition-gallery">{{ exhibition.galleryName }}</view>
          <view class="exhibition-date">{{ formatDate(exhibition.createdAt) }}</view>
          <view class="image-count">{{ exhibition.imageCount || 0 }} 张图片</view>
        </view>
        <view class="select-arrow">→</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { getRecordList } from '@/services/api/backendApi'

// 响应式数据
const isLoading = ref(true)
const exhibitions = ref([])

// 页面加载时获取展览列表
onMounted(async () => {
  await loadExhibitions()
})

onBeforeUnmount(() => {
  uni.$off('exhibitionSaved', prependNewExhibition)
})

// 加载展览列表
async function loadExhibitions() {
  try {
    isLoading.value = true
    console.log('📥 [导入-选择展览] 开始加载展览列表')
    const res = await getRecordList(1, 50)
    console.log('✅ [导入-选择展览] 列表接口返回:', res)
    const data = res.data || res
    const list = data.records || []
    exhibitions.value = Array.isArray(list) ? list : []
    console.log('📦 [导入-选择展览] total:', data.total, 'records length:', exhibitions.value.length)
    // 监听新建展览事件，实时插入
    uni.$off('exhibitionSaved', prependNewExhibition)
    uni.$on('exhibitionSaved', prependNewExhibition)
  } catch (error) {
    console.error('加载展览列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

function prependNewExhibition(newRecord) {
  console.log('🆕 [导入-选择展览] 收到新建展览事件:', newRecord)
  if (!newRecord) return
  const record = {
    recordId: newRecord.recordId || newRecord.id,
    title: newRecord.title,
    galleryName: newRecord.museum || newRecord.galleryName,
    createdAt: newRecord.createdAt || new Date().toISOString(),
    coverImage: newRecord.coverImageUrl || newRecord.coverImage,
    imageCount: newRecord.imageCount || 0
  }
  const idx = exhibitions.value.findIndex(r => (r.recordId || r.id) === record.recordId)
  if (idx > -1) {
    const next = [...exhibitions.value]
    next.splice(idx, 1)
    exhibitions.value = [record, ...next]
  } else {
    exhibitions.value = [record, ...exhibitions.value]
  }
}

// 选择展览
function selectExhibition(exhibition) {
  console.log('选择展览:', exhibition)
  
  // 跳转到图片选择页面
  uni.navigateTo({
    url: `/pages/image-import/image-selector?exhibitionId=${exhibition.recordId}&exhibitionTitle=${encodeURIComponent(exhibition.title)}`,
    success: () => {
      console.log('跳转到图片选择页面')
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败',
        icon: 'none'
      })
    }
  })
}

// 创建新展览
function createNewExhibition() {
  console.log('创建新展览')
  
  uni.navigateTo({
    url: '/pages/footprint/create?mode=import',
    success: () => {
      console.log('跳转到新建展览页面')
    }
  })
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'short',
    day: 'numeric'
  })
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: #1a1a1a;
  padding: 20px;
}

.header {
  text-align: center;
  margin-bottom: 30px;
  
  .title {
    font-size: 28px;
    font-weight: 700;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    margin-bottom: 10px;
    letter-spacing: 1px;
  }
  
  .subtitle {
    font-size: 16px;
    color: #a0826d;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  
  .loading-text {
    font-size: 16px;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  
  .empty-icon {
    font-size: 64px;
    margin-bottom: 20px;
    opacity: 0.6;
  }
  
  .empty-text {
    font-size: 20px;
    color: #ffffff;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 600;
    margin-bottom: 10px;
  }
  
  .empty-hint {
    font-size: 14px;
    color: #a0826d;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    margin-bottom: 30px;
  }
  
  .create-btn {
    background: linear-gradient(135deg, #d4af37, #f4e4bc);
    color: #ffffff;
    border: none;
    padding: 12px 24px;
    border-radius: 25px;
    font-size: 16px;
    font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(212, 175, 55, 0.3);
  }
}

.exhibition-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.exhibition-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(245, 242, 237, 0.9));
  border-radius: 20px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 8px 24px rgba(212, 175, 55, 0.15);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2px);
    box-shadow: 0 4px 16px rgba(212, 175, 55, 0.2);
  }
  
  .exhibition-image {
    width: 80px;
    height: 80px;
    border-radius: 15px;
    overflow: hidden;
    margin-right: 20px;
    flex-shrink: 0;
    
    .cover-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  
  .exhibition-info {
    flex: 1;
    
    .exhibition-title {
      font-size: 18px;
      font-weight: 600;
      color: #ffffff;
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      margin-bottom: 5px;
    }
    
    .exhibition-gallery {
      font-size: 14px;
      color: #a0826d;
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      margin-bottom: 3px;
    }
    
    .exhibition-date {
      font-size: 12px;
      color: #a0826d;
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      margin-bottom: 3px;
    }
    
    .image-count {
      font-size: 12px;
      color: #d4af37;
      font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
      font-weight: 500;
    }
  }
  
  .select-arrow {
    font-size: 24px;
    color: #d4af37;
    font-weight: bold;
    margin-left: 15px;
  }
}
</style>
